

const router = require('express').Router();
const joi = require('joi');
const joiValidate = require('../../../utils/joiValidate');
const verifyUser = require('../../../utils/jwtHanlder');
const applyService = require('../../../service/user/applyService');
const LockUtil = require('../../../utils/lockUtil');
const ErrorCode = require('../../../utils/errorCode');
/**
 * @apiDefine Apply  申请接口
 */

/**
 * @api {post} /v1/user/apply/refund/deal  处理退款申请
 * @apiVersion 1.0.0
 * @apiName ApplyRefund
 * @apiGroup  Apply
 *
 * @apiDescription 教练登陆
 *
 * @apiParam {Number} applyId  申请Id
 * @apiParam {Number=1,-1} status  处理结果（1代表通过，-1代表不通过）
 *
 * @apiExample Example usage:
 * curl -i http://localhost:3502/v1/user/apply/refund/deal
 *
 * @apiSuccess {Number} code      请求结果编码，0：正常， 其他为异常
 * @apiSuccess {string} message    请求结果编码对应的message
 *
 * @apiSuccessExample 正常响应：
 *     HTTP/1.1 200
 *     {
          "code": 200,
          "message": "请求成功"
       }
 *
 *
 * @apiError  ServerError  服务器异常
 *
 * @apiErrorExample Response (example):
 *     HTTP/1.1 500 ServerError
 *     {
 *       "code": 500,
 *       "message": "服务器异常"
 *     }
 */
router.post('/refund/deal', verifyUser.verify(), joiValidate(joi.object().keys({
  applyId: joi.number().required().label('请填入申请Id'),
  status: joi.number().valid([1, -1]).required().label('请确定处理结果')
})), (req, res, next) => {
  const { userId } = req.user;
  const { applyId, status } = req.body;
  const lockUtil = new LockUtil(`apply:refund:`, applyId , 120);
  return lockUtil.tryLock()
    .then(() => applyService.dealApply({ userId, applyId, status }))
    .then((data) => {
      // 删除请求锁
      lockUtil.unlock().catch(console.error);
      res.success(data);
    })
    .catch((err) => {
      // 非频繁访问时删除频繁队列key
      if (err.code !== ErrorCode.FREQUENT_REQUEST) lockUtil.unlock().catch(console.error);
      next(err);
    });
});


/**
 * @api {get} /v1/user/apply/refund/list  获取退款申请
 * @apiVersion 1.0.0
 * @apiName ApplyRefundList
 * @apiGroup  Apply
 *
 * @apiDescription 获取退款申请
 *
 * @apiParam {Number} offset 分页参数
 * @apiParam {Number} limit 分页参数
 * @apiParam {Number=0,1,2} kind (我发起的1， 我收到的2， 全部0)
 *
 * @apiExample Example usage:
 * curl -i http://localhost:3502/v1/user/apply/refund/list
 *
 * @apiSuccess {Number} code      请求结果编码，0：正常， 其他为异常
 * @apiSuccess {string} message    请求结果编码对应的message
 * @apiSuccess {Object[]} data    结果集
 * @apiSuccess {Object[]} data.list    结果集
 * @apiSuccess {Number} data.count    数量
 * @apiSuccess {Number} data.list.refundStatus    (1,代表初始状态,10全部退款,-1拒绝退款)
 * @apiSuccess {Number} data.list.status   // 退款申请状态(0代表初始状态，1代表通过，-1代表拒绝)
 * @apiSuccess {Number} data.list.type     // (退款申请类型， 1代表学员发起申请退款, 2代表教练发起申请退款)
 * @apiSuccess {Number} data.list.courseId    课程Id
 * @apiSuccess {Number} data.list.applyUserId    申请人用户Id
 * @apiSuccess {Number} data.list.handleUserId    处理人用户Id
 * @apiSuccess {String} data.list.createTime    申请时间
 * @apiSuccess {String} data.list.applyUserName    申请人
 * @apiSuccess {String} data.list.handleUserName    处理人
 * @apiSuccess {String} data.list.courseName    课程名称
 * @apiSuccess {String} data.list.courseType    课程类型
 * @apiSuccess {Number} data.list.isSelf    是否是自己发起的（1代表是自己发起的，0代表是别人发起）
 *
 * @apiSuccessExample 正常响应：
 *     HTTP/1.1 200
 *     {
          "code": 200,
          "message": "请求成功"，
          "data": {
              "list": [
                  {
                      "refundStatus": 1,
                      "status": 1,
                      "type": 1,
                      "courseId": 2,
                      "applyUserId": 3,
                      "handleUserId": 1,
                      "createTime": "2019-07-16 17:50:23",
                      "applyUserName": "王树浩",
                      "handleUserName": "文坦",
                      "courseName": "团课",
                      "courseType": 1,
                      "isSelf": 0
                  }
              ],
              "count": 1
          }
       }
 *
 *
 * @apiError  ServerError  服务器异常
 *
 * @apiErrorExample Response (example):
 *     HTTP/1.1 500 ServerError
 *     {
 *       "code": 500,
 *       "message": "服务器异常"
 *     }
 */
router.get('/refund/list', verifyUser.verify(), joiValidate(joi.object().keys({
  offset: joi.number().label('请填入分页参数'),
  limit: joi.number().label('请填入分页参数'),
  kind: joi.number().valid([0, 1, 2]).required().label('请传入查询tab')
})), (req, res, next) => {
  let { offset, limit, kind } = req.query;
  offset = offset && Number(offset) || 0;
  limit = limit && Number(limit) || 20;
  kind = Number(kind);
  const { userId } = req.user;
  applyService.queryRefundApplyList({ kind, offset, limit, userId })
    .then((data) => res.success(data))
    .catch(e => next(e))
});

module.exports = router;
